/**
 * NotificationCase.h
 *
 * The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License");
 * you may not use this file except in compliance with the License. You may obtain a copy of the License 
 * at http://www.mozilla.org/MPL/
 * Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND,
 * either express or implied. See the License for the specific language governing rights and limitations 
 * under the License.
 *
 * The Original Code is gcast-toolbox4iphone.
 *
 * The Initial Developers of the Original Code is Giannandrea Castaldi.
 */

#import "FrequencyMaker.h"

@interface FrequencyMaker ()
@property(nonatomic,retain) BOOL (^block)(int count);
@property(nonatomic,retain) NSTimer* timer;
@property(nonatomic,assign) NSUInteger count;
- (void)nextNotification;
@end

@implementation FrequencyMaker
@synthesize block, timer, count;

+ (id)frequencyMakerWithTimeInterval:(NSTimeInterval)aTimeInterval Block:(BOOL(^)(int count))aBlock {
  return [[[self alloc] initWithTimeInterval:aTimeInterval Block:aBlock] autorelease];
}

- (id)initWithTimeInterval:(NSTimeInterval)aTimeInterval Block:(BOOL(^)(int count))aBlock {
  if ((self = [super init])) {
    self.block = aBlock;
    count = 0;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:aTimeInterval
                                                  target:self
                                                selector:@selector(nextNotification)
                                                userInfo:nil
                                                 repeats:YES];
    [self nextNotification];
  }
  return self;
}

- (void)dealloc {
  [self.timer invalidate];
  [timer release];
  [block release];
  [super dealloc];
}

- (void)nextNotification {
  BOOL goAhread = self.block(count);
  if (goAhread) {
    count++;
  }
  else {
    [self.timer invalidate];
    self.timer = nil;
  }
}


@end
